package cn.walmt.service;

import cn.walmt.entity.Post;
import cn.walmt.entity.User;
import cn.walmt.entity.Vote;
import cn.walmt.mapper.PostMapper;
import cn.walmt.mapper.VoteMapper;
import cn.walmt.pojo.PostIdAndUserId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.GsonUtil;

import javax.servlet.http.HttpSession;

/**
 * 点赞功能方面
 * Created by walmt on 2018/5/26.
 */
@Service
@Transactional
public class VoteService {

    @Autowired
    private VoteMapper voteMapper;
    @Autowired
    private PostMapper postMapper;

    /**
     * 点赞功能
     * 没点赞过则添加点赞数据
     * 点赞又取消了（valid为false）则将valid设置为true
     *
     * @param postId 动态id
     * @param session
     * @return
     */
    public String vote(Integer postId, HttpSession session) {
        // 获取是否存在点赞记录
        User user = (User) session.getAttribute("user");
        PostIdAndUserId postIdAndUserId = new PostIdAndUserId(postId, user.getId());
        Vote vote = voteMapper.selectByPostIdAndUserId(postIdAndUserId);

        // 实现点赞
        if (vote == null || !vote.getValid()) {
            if (vote == null) { // 没点赞过
                vote = new Vote();
                vote.setPostId(postId);
                vote.setUserId(user.getId());
                vote.setValid(true);
                voteMapper.insertSelective(vote);
            } else { // 点赞过又取消了，再次点赞
                vote.setValid(Boolean.TRUE);
                voteMapper.updateByPrimaryKey(vote);
            }
            // 修改动态的点赞数量
            postMapper.incrementVotes(postId);
        }

        return GsonUtil.getSuccessJson();
    }

    /**
     * 取消点赞
     * 先从数据库中获取数据，不存在则报错
     * 判断valid是否有效，有效则更新为无效
     * 如果是无效则报错
     *
     * @param postId
     * @param session
     * @return
     */
    public String cancelVote(Integer postId, HttpSession session) {
        // 获取是否存在点赞记录
        User user = (User) session.getAttribute("user");
        PostIdAndUserId postIdAndUserId = new PostIdAndUserId(postId, user.getId());
        Vote vote = voteMapper.selectByPostIdAndUserId(postIdAndUserId);

        if (vote != null && vote.getValid()) { // 判断是否点赞了
            // 取消点赞
            vote.setValid(Boolean.FALSE);
            voteMapper.updateByPrimaryKey(vote);
            postMapper.decrementVotes(postId);
        }

        return GsonUtil.getSuccessJson();
    }
}
